package Servelts;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadBase.FileSizeLimitExceededException;
import org.apache.commons.fileupload.FileUploadBase.SizeLimitExceededException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import daoFactory.DaoFactory;
import daoImpls.CategoryDAOImpl;
import daoImpls.GoodDAOImpl;
import vo.Category;
import vo.Good;
import vo.PetObject;

@WebServlet("/listProduct")
public class ProductListServlet extends HttpServlet {
	
	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String status = request.getParameter("status");
		String page = (String) request.getSession().getAttribute("page");
		String url = "error.jsp";
		//查询所有
		if(status.equals("selectall")){
			int start=request.getParameter("start")==null?0:Integer.parseInt(request.getParameter("start"));
			//通过page实现类获得总页数，这里为每页数目
			 int pageSize = 4;
		     int totalPage = DaoFactory.getPageFactory().getGoodTotal(pageSize); 
		     int prePage = start-1;
		     if(prePage<0) prePage = 0;
		     int nextPage = start+1;
		     if(nextPage+1>totalPage) nextPage = totalPage-1;
			
			request.setAttribute("totalPage", totalPage);
			request.setAttribute("prePage", prePage); 
	       	request.setAttribute("nextPage", nextPage);
	       	
			List<Good> products = DaoFactory.getGoodFactory().list(start*pageSize,pageSize);
	        request.setAttribute("products", products);
	        request.getSession().setAttribute("size", products.size());
	        int totalsize = DaoFactory.getGoodFactory().list().size();
	        request.setAttribute("totalsize", totalsize);
	        request.setAttribute("star", start+1);
//	        url = "listProduct.jsp";
	        if(page.equals("back")){
	        	url = "listProduct.jsp";
	        }
	        else
	        	url = "shopProduct.jsp";
		}
		if(status.equals("select")){
			String gid = request.getParameter("gid");
			Good good = DaoFactory.getGoodFactory().get(gid);
			String cate = DaoFactory.getCategoryFactory().get(good.getCatID()).getCatName();
			request.setAttribute("good", good);
			request.setAttribute("cateName", cate);
			
			url = "shopbuy.jsp";
		}
		//模糊查询
		if(status.equals("selectlike")){
			//.getBytes("ISO-8859-1"),"UTF-8")
			String s = request.getParameter("key");
			System.out.println(s);
			List<Good> list = (List<Good>) DaoFactory.getGoodFactory().list(s);
			request.setAttribute("products", list);
			//url = "listProduct.jsp";
			url = "shopProduct.jsp";
			if (request.getParameter("page") != null) 
				url = "listProduct.jsp";
			 
		}		
		//商品详情
		if(status.equals("Goodinfo")){
			Good good = DaoFactory.getGoodFactory().get(request.getParameter("id"));
			String cate = DaoFactory.getCategoryFactory().get(good.getCatID()).getCatName();
			request.setAttribute("cname",cate);
			request.setAttribute("good",good);
			request.setAttribute("num", good.getGnum());
			
			List<PetObject> catelist = DaoFactory.getCategoryFactory().list();
			for (int i = 0; i < catelist.size(); i++) {
				Category cates = (Category) catelist.get(i);
				if(cates.getCatName().equals(cate))
					catelist.remove(i);
			}
			request.setAttribute("catlist",catelist );
			url = "GoodInfo.jsp";
		}
		//商品更新
		if(status.equals("update")){
			/*Good good = DaoFactory.getGoodFactory().get(request.getParameter("gid"));
			good.setgName(request.getParameter("gname"));
			good.setgMsg(request.getParameter("gmsg"));
			good.setgPrice(Double.parseDouble(request.getParameter("gprice")));
			good.setGnum(Integer.parseInt(request.getParameter("gnum")));
			good.setCatID(request.getParameter("cname"));
			DaoFactory.getGoodFactory().update(good);*/
			String[] Values = new String[7];
			int i=0;
			PrintWriter writer = response.getWriter();
			DiskFileItemFactory factory = new DiskFileItemFactory();
			ServletFileUpload upload = new ServletFileUpload(factory);
			upload.setHeaderEncoding("UTF-8");
			//设置单个文件上传上限为：10m
			upload.setFileSizeMax(1024*1024*10);
			//设置总文件上传上限为：10m
			upload.setSizeMax(1024*1024*10);
			//获取上传文件的真实路径（服务器根目录的upload）
			String realPath = getServletContext().getRealPath("/Resources/images");
			String src = null;
			try {
				//通过ServletFileUpload中的parseRequest()方法，将表单项解析为List<FileItem>
				List<FileItem> list = upload.parseRequest(request);
				for (FileItem fileItem : list) {
					if(fileItem.getSize()>0) {
						if(fileItem.isFormField() == false) {
							//时间戳命名
							String fName = System.currentTimeMillis() + ".jpg";
							//创建File为，上传文件预留位置（真实路径(D:dd/)+文件名）
							File file = new File(realPath+"/"+fName);
							if(!file.exists()){
								file.getParentFile().mkdir();
							}
							//文件表单项，write()，将文件上传到服务器
							fileItem.write(file);
							//相对路径
							src = "Resources/images/" + fName;
							//System.out.println(src);
						}else {
							//普通表单项
							Values[i] = fileItem.getString();
							i++;
						}
					}
				}
				Good good = DaoFactory.getGoodFactory().get(Values[0]);
				if(src!=null){
					if(good.getGsrc()!=null){
						String realpath = getServletContext().getRealPath("/Resources/images");
						File oldfile = new File(realpath + "/" + good.getGsrc().split("/")[2]);
						if(oldfile.isFile()&&oldfile.exists())
							oldfile.delete();
					}
					good.setGsrc(src);
				}
				good.setgName(new String(Values[1].getBytes("ISO-8859-1"),"UTF-8"));
				good.setCatID(new String(Values[2].getBytes("ISO-8859-1"),"UTF-8"));
				good.setgPrice(Double.parseDouble(Values[3]));
				good.setGnum(Integer.parseInt(Values[4]));
				good.setgMsg(new String(Values[5].getBytes("ISO-8859-1"),"UTF-8"));
				System.out.println(good);
				DaoFactory.getGoodFactory().update(good);
			}catch (FileSizeLimitExceededException e) {
				System.out.println(e.getMessage());
			}catch (SizeLimitExceededException e) {
				System.out.println(e.getMessage());
			}catch (Exception e) {
				System.out.println("上传失败 " + e.getMessage());
		}
			url = "listProduct?status=selectall";
		}
		//删除
		if(status.equals("delete")){
			String gid = request.getParameter("gid");
			DaoFactory.getGoodFactory().delete(gid);
			url = "listProduct?status=selectall";
		}
		//范围删除
		if(status.equals("deletequery")){
			String ids = request.getParameter("ids");
			DaoFactory.getGoodFactory().deleteQuery(ids);
			url = "listProduct?status=selectall";
		}
		//商品添加
		if(status.equals("add")){
			Good good = new Good();
			String[] Values = new String[7];
			int i=0;
			PrintWriter writer = response.getWriter();
			DiskFileItemFactory factory = new DiskFileItemFactory();
			ServletFileUpload upload = new ServletFileUpload(factory);
			upload.setHeaderEncoding("UTF-8");
			//设置单个文件上传上限为：10m
			upload.setFileSizeMax(1024*1024*10);
			//设置总文件上传上限为：10m
			upload.setSizeMax(1024*1024*10);
			//获取上传文件的真实路径（服务器根目录的upload）
			String realPath = getServletContext().getRealPath("/Resources/images");
			String src = null;
			try {
				//通过ServletFileUpload中的parseRequest()方法，将表单项解析为List<FileItem>
				List<FileItem> list = upload.parseRequest(request);
				for (FileItem fileItem : list) {
					if(fileItem.getSize()>0) {
						if(fileItem.isFormField() == false) {
							//时间戳命名
							String fName = System.currentTimeMillis() + ".jpg";
							//创建File为，上传文件预留位置（真实路径(D:dd/)+文件名）
							File file = new File(realPath+"/"+fName);
							if(!file.exists()){
								file.getParentFile().mkdir();
							}
							//文件表单项，write()，将文件上传到服务器
							fileItem.write(file);
							
							//相对路径
							src = "Resources/images/" + fName;
							if(src!=null) good.setGsrc(new String(src));
						}else {
							//普通表单项
							Values[i] = fileItem.getString();
							i++;
						}
					}
				}
				good.setgName(new String(Values[0].getBytes("ISO-8859-1"),"UTF-8"));
				good.setCatID(new String(Values[1].getBytes("ISO-8859-1"),"UTF-8"));
				good.setgPrice(Double.parseDouble(Values[2]));
				good.setGnum(Integer.parseInt(Values[3]));
				good.setgMsg(new String(Values[4].getBytes("ISO-8859-1"),"UTF-8"));
				
				DaoFactory.getGoodFactory().add(good);
			}catch (FileSizeLimitExceededException e) {
				writer.write("上传失败，单个文件上传大小不能超过1k!");
				System.out.println(e.getMessage());
			}catch (SizeLimitExceededException e) {
				System.out.println(e.getMessage());
				writer.write("上传失败，总文件上传大小不能超过2k!");
			}catch (Exception e) {
				System.out.println(e.getMessage());
		}
			url = "listProduct?status=selectall";
			System.out.println("Good add: " + good);
		}
		//跳转添加
		if(status.equals("addjsp")){
			List<PetObject> catelist = DaoFactory.getCategoryFactory().list();
			request.setAttribute("catlist",catelist);
			url = "Goodadd.jsp";
		}
		
        request.getRequestDispatcher(url).forward(request, response);
        
	}
	//F:\learning\JAVA\Java_Demo\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\PetShop\Resources\images
	

}
